package it.uniroma3.dia.ia.textcategorization.model;

import it.uniroma3.dia.ia.textcategorization.persistence.TextPersistenceManagerFactory;
import it.uniroma3.dia.ia.textcategorization.persistence.TextPersistenceManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 
 * This class represents text documents.
 * 
 * @author Marco Liceti
 *
 */
public final class Text {

	private final String id;
	
	private final static TextPersistenceManager PERSISTENCE_MANAGER = TextPersistenceManagerFactory.getTextPersistenceManager();

	public Text(InputStream inputStream) {
		this.id = PERSISTENCE_MANAGER.saveText(inputStream);
	}
	
	public InputStream asInputStream() {
		return PERSISTENCE_MANAGER.loadText(this.id);
	}

	@Override
	protected void finalize() {
		PERSISTENCE_MANAGER.deleteText(this.id);
	}

	@Override
	public boolean equals(Object obj) {
		if (obj == this) {
			return true;
		} else if (obj instanceof Text) {
			return this.id.equals(id);
		}
		return false;
	}

	@Override
	public int hashCode() {
		return this.id.hashCode();
	}

	@Override
	public String toString() {
		String result = null;
		
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(this.asInputStream()));
			StringBuilder sb = new StringBuilder();
			String line = reader.readLine();
			while (line != null) {
				sb.append(line + "\n");
				line = reader.readLine();
			}
			result = sb.toString();
		} catch (IOException e) {
			// In case of an exception,
			// simply return null
		}
		
		return result;
	}

}
